

/**
 * 加密处理
 */
export const encryption = (params) => {
  let {
    data,
    type,
    param,
    key
  } = params
  const result = JSON.parse(JSON.stringify(data))
  if (type === 'Base64') {
    param.forEach(ele => {
      result[ele] = btoa(result[ele])
    })
  } else {
    param.forEach(ele => {
      var data = result[ele]
      key = CryptoJS.enc.Latin1.parse(key)
      var iv = key
      // 加密
      var encrypted = CryptoJS.AES.encrypt(
        data,
        key, {
        iv: iv,
        mode: CryptoJS.mode.CBC,
        padding: CryptoJS.pad.ZeroPadding
      })
      result[ele] = encrypted.toString()
    })
  }
  return result
}

/**
 * 设置浏览器头部标题
 */
export const setTitle = function (title) {
  title = title ? `${title}—— panda` : 'panda'
  window.document.title = title
}
/**
 * 浏览器判断是否全屏
 */
export const fullscreenToggel = () => {
  if (fullscreenEnable()) {
    exitFullScreen()
  } else {
    reqFullScreen()
  }
}
/**
 * esc监听全屏
 */
export const listenfullscreen = (callback) => {
  function listen() {
    callback()
  }
  document.addEventListener('fullscreenchange', function (e) {
    listen()
  })
  document.addEventListener('mozfullscreenchange', function (e) {
    listen()
  })
  document.addEventListener('webkitfullscreenchange', function (e) {
    listen()
  })
  document.addEventListener('msfullscreenchange', function (e) {
    listen()
  })
}

/**
 * 浏览器判断是否全屏
 */
export const fullscreenEnable = () => {
  var isFullscreen = document.fullscreenEnabled ||
    window.fullScreen ||
    document.mozFullscreenEnabled ||
    document.webkitIsFullScreen
  return isFullscreen
}

/**
 * 浏览器全屏
 */
export const reqFullScreen = () => {
  if (document.documentElement.requestFullScreen) {
    document.documentElement.requestFullScreen()
  } else if (document.documentElement.webkitRequestFullScreen) {
    document.documentElement.webkitRequestFullScreen()
  } else if (document.documentElement.mozRequestFullScreen) {
    document.documentElement.mozRequestFullScreen()
  }
}

/**
 * 浏览器退出全屏
 */
export const exitFullScreen = () => {
  if (document.documentElement.requestFullScreen) {
    document.exitFullScreen()
  } else if (document.documentElement.webkitRequestFullScreen) {
    document.webkitCancelFullScreen()
  } else if (document.documentElement.mozRequestFullScreen) {
    document.mozCancelFullScreen()
  }
}

/**
 * 递归寻找子类的父类
 */
export const findParent = (menu, id) => {
  for (let i = 0; i < menu.length; i++) {
    if (menu[i].children.length !== 0) {
      for (let j = 0; j < menu[i].children.length; j++) {
        if (menu[i].children[j].id === id) {
          return menu[i]
        } else {
          if (menu[i].children[j].children.length !== 0) {
            return findParent(menu[i].children[j].children, id)
          }
        }
      }
    }
  }
}

/**
 * 总体路由处理器
 */
export const resolveUrlPath = (url, name) => {
  let reqUrl = url
  if (url.indexOf('#') !== -1 && url.indexOf('http') === -1) {
    const port = reqUrl.substr(reqUrl.indexOf(':'))
    reqUrl = `/myiframe/urlPath?src=${baseUrl}${port}${reqUrl.replace('#', '').replace(port, '')}}&name=${name}`
  } else if (url.indexOf('http') !== -1) {
    reqUrl = `/myiframe/urlPath?src=${reqUrl}&name=${name}`
  } else {
    reqUrl = `${reqUrl}`
  }
  return reqUrl
}

/**
 * 总体路由设置器
 */
export const setUrlPath = ($route) => {
  let value = ''
  if ($route.query.src) {
    value = $route.query.src
  } else {
    value = $route.path
  }
  return value
}

/**
 * 动态插入css
 */
export const loadStyle = url => {
  const link = document.createElement('link')
  link.type = 'text/css'
  link.rel = 'stylesheet'
  link.href = url
  const head = document.getElementsByTagName('head')[0]
  head.appendChild(link)
}



/**
 * 根据字典的value查找对应的index
 */
export const findArray = (dic, value) => {
  for (let i = 0; i < dic.length; i++) {
    if (dic[i].value === value) {
      return i
    }
  }
  return -1
}

/**
 * 生成随机len位数字
 */
export const randomLenNum = (len, date) => {
  let random = ''
  random = Math.ceil(Math.random() * 100000000000000).toString().substr(0, typeof len === 'number' ? len : 4)
  if (date) random = random + Date.now()
  return random
}

// 获取30天前日期
export function getAgoDay() {
  var date1 = new Date()
  var date2 = new Date(date1)
  //-30为30天前，+30可以获得30天后的日期
  date2.setDate(date1.getDate() - 30)
  //30天前（月份判断是否小于10，小于10的前面+0）
  var year = date2.getFullYear()
  var mon = date2.getMonth() + 1
  var day = date2.getDate()
  if (mon < 10) {
    mon = '0' + mon
  }
  if (day < 10) {
    day = '0' + day
  }
  return year + '' + mon + '' + day + '000000'
}
//获取当前日期
export function getTodayDate() {
  var date = new Date()
  var year = date.getFullYear()
  var mon = date.getMonth() + 1
  var day = date.getDate()
  if (mon < 10) {
    mon = '0' + mon
  }
  if (day < 10) {
    day = '0' + day
  }
  return year + '' + mon + '' + day + '235959'
}

//计算两个时间差
export function CalculateTime(startTime) {
  var dateEnd = new Date() //获取当前时间
  if (!(startTime instanceof Date)) {
    startTime = new Date(startTime).getTime()
  }
  var dateDiff = dateEnd.getTime() - startTime //时间差的毫秒数
  var dayDiff = Math.floor(dateDiff / (24 * 3600 * 1000)) //计算出相差天数
  var leave1 = dateDiff % (24 * 3600 * 1000) //计算天数后剩余的毫秒数
  var hours = Math.floor(leave1 / (3600 * 1000)) //计算出小时数
  //计算相差分钟数
  var leave2 = leave1 % (3600 * 1000) //计算小时数后剩余的毫秒数
  var minutes = Math.floor(leave2 / (60 * 1000)) //计算相差分钟数
  if (minutes < 10) {
    minutes = '0' + minutes
  }
  //计算相差秒数
  var leave3 = leave2 % (60 * 1000) //计算分钟数后剩余的毫秒数
  var seconds = Math.round(leave3 / 1000)
  if (seconds < 10) {
    seconds = '0' + seconds
  }
  var timeFn = '' + hours + ':' + minutes + ':' + seconds
  return timeFn
}

//排序函数
export function quickSort(arr) {
  arr.forEach(function (item) {
    let temp = item[eachName];
    item.sortName = temp;
  });
  let resultArray = arr.sort(
    function compareFunction(param1, param2) {
      return param1.sortName.localeCompare(param2.sortName, "zh");
    }
  );
  return resultArray;
};

//按大小排序
export function compare(property) {
  return function (a, b) {
    var value1 = a[property]
    var value2 = b[property]
    return value1 - value2
  }
}

//判断两个时间差是否超过24小时
export function over24Hours(startTime) {
  var dateEnd = new Date() //获取当前时间
  if (!(startTime instanceof Date)) {
    startTime = new Date(startTime.replace(/-/g, '/')).getTime()
  }
  var dateDiff = dateEnd.getTime() - startTime //时间差的毫秒数
  var dayDiff = Math.floor(dateDiff / (24 * 3600 * 1000)) //计算出相差天数
  return dayDiff > 0 ? false : true
}


/**
 * map 生成组织树
 * @param config  map
 * @param parentId  父级id名
 * @param id  id名
 * @param name  label名
 */
export function toTree(config, parentId, id, name) {
  // 删除 所有 children,以防止多次调用
  config.forEach(function (item) {
    delete item.children
  })
  // 将数据存储为 以 id 为 KEY 的 map 索引数据列
  var map = {}
  config.forEach(function (item) {
    // 树 的label
    item.label = item[name]
    map[item[id]] = item
  })
  var val = []
  config.forEach(function (item) {
    // 以当前遍历项，的pid,去map对象中找到索引的id
    var parent = map[item[parentId]]
    // 如果找到索引，那么说明此项不在顶级当中,那么需要把此项添加到，他对应的父级中
    if (parent) {
      ; (parent.children || (parent.children = [])).push(item)
    } else {
      //如果没有在map中找到对应的索引ID,那么直接把 当前的item添加到 val结果集中，作为顶级
      val.push(item)
    }
  })
  return val
}


